package com.tuyrt.`as`.proj.main.biz.detail

import android.text.TextUtils
import androidx.databinding.library.BuildConfig
import androidx.lifecycle.*
import com.tuyrt.`as`.proj.main.http.ApiFactory
import com.tuyrt.`as`.proj.main.http.api.DetailApi
import com.tuyrt.`as`.proj.main.http.api.FavoriteApi
import com.tuyrt.`as`.proj.main.model.DetailModel
import com.tuyrt.`as`.proj.main.model.Favorite
import com.tuyrt.hi.library.restful.HiCallback
import com.tuyrt.hi.library.restful.HiResponse

/**
 * author: Administrator on 2021/7/16.
 * desc:
 */
class DetailViewModel(val goodsId: String?) : ViewModel() {

    companion object {

        private class DetailViewModelFactory(val goodsId: String?) : ViewModelProvider.NewInstanceFactory() {

            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                try {
                    val constructor = modelClass.getConstructor(String::class.java)
                    return constructor.newInstance(goodsId)
                } catch (e: Exception) {
                    // ignore
                }
                return super.create(modelClass)
            }
        }

        fun get(goodsId: String?, viewModelStore: ViewModelStore): DetailViewModel {
            return ViewModelProvider(viewModelStore, DetailViewModelFactory(goodsId)).get(DetailViewModel::class.java)
        }
    }

    val pageData = MutableLiveData<DetailModel?>()
    fun queryGoodsDetail(){
        if (!TextUtils.isEmpty(goodsId)) {
            ApiFactory.create(DetailApi::class.java).queryDetail(goodsId!!)
                .enqueue(object : HiCallback<DetailModel> {
                    override fun onSuccess(response: HiResponse<DetailModel>) {
                        if (response.successful() && response.data != null) {
                            pageData.postValue(response.data)
                        } else {
                            pageData.postValue(null)
                        }
                    }

                    override fun onFailed(throwable: Throwable) {
                        pageData.postValue(null)
                        if (BuildConfig.DEBUG) {
                            throwable.printStackTrace()
                        }
                    }
                })
        }
    }

    fun toggleFavorite(): LiveData<Boolean?> {
        val toggleFavoriteLiveData = MutableLiveData<Boolean?>()
        if (!TextUtils.isEmpty(goodsId)) {
            ApiFactory.create(FavoriteApi::class.java)
                .favorite(goodsId!!)
                .enqueue(object :HiCallback<Favorite>{
                    override fun onSuccess(response: HiResponse<Favorite>) {
                       toggleFavoriteLiveData.postValue(response.data?.isFavorite)
                    }

                    override fun onFailed(throwable: Throwable) {
                        toggleFavoriteLiveData.postValue(null)
                    }
                })
        }
        return toggleFavoriteLiveData
    }
}